package com.org.redis.limit;

import com.sun.jmx.snmp.tasks.ThreadService;
import org.redisson.Redisson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.Semaphore;



@RestController
public class Controller {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("limit")
    @Limiter(value = "limit_test",request = 5,expire = 10)
    public String test(){
        redisTemplate.opsForValue().set("k2","v2");
        return (String) redisTemplate.opsForValue().get("k2");
    }

    private static volatile Semaphore semaphore = new Semaphore(2);

    @GetMapping("/test")
    public void testSemaphore(){
        try {
            //semaphore.acquire();
            boolean b = semaphore.tryAcquire();
            System.out.println(b + " --> " + Thread.currentThread().getName() + " --> begin");
            Thread.sleep(10000);
            System.out.println(Thread.currentThread().getName() + " --> end");
        }catch (Exception e){
            //TODO DO NOTHING
        }finally {
            semaphore.release();
        }
    }

    @GetMapping("/testip")
    @Saver(key = "ip")
    public String testIp(HttpServletRequest request){
        return request.getRemoteAddr();
    }

}
